package org.example.ruoxing_admin_springboot3.utils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import lombok.Getter;
import lombok.Setter;
import org.example.ruoxing_admin_springboot3.dao.UserInfoDao;
import java.util.Date;
/**
 * @description 生成token的工具类
 * @author 莫若省
 * @createTime 2024/4/29
*/
public class JWTUtils {
    // TODO 请替换为自己的密钥
    // 密钥
    private static final String SECRET_KEY = "065BB4F5267088B708D112F38654AA59";
    // 过期时间 8小时
    private static final long EXPIRATION_TIME = 8 * 60 * 60 * 1000;
    @Setter
    @Getter
    public static class Token {
        private String token;
        private String userId;
        private String userName;
        private String userAvatar;
        public Token(String token,UserInfoDao userInfo) {
            this.token = token;
            this.userId = userInfo.getUserId();
            this.userName = userInfo.getUserName();
            this.userAvatar = userInfo.getUserAvatar();
        }
    }
    /**
     * @description 创建token
     * @author 莫若省
     * @createTime 2024/5/6
    */
    public static Token createTokenMap(UserInfoDao userInfo) {
        return new Token(Jwts.builder()
                .setId(userInfo.getUserId())//用户id
                .signWith(io.jsonwebtoken.SignatureAlgorithm.HS512, SECRET_KEY)//加密算法和密钥
                .setExpiration(new Date(TimestampUtil.getCurrentMillisTimestamp() + EXPIRATION_TIME))//过期时间
                .compact(), userInfo);
    }
    /**
     * @description 解析token是否过期
     * @author 莫若省
     * @createTime 2024/5/10
    */
    public static boolean isTokenExpired(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getExpiration();
            return false;
        }catch (ExpiredJwtException e) {
            return true;
        }
    }
    /**
     * @description 简析token获取用户id
     * @author 莫若省
     * @createTime 2024/5/6
     * @return java.lang.String 用户的user_id
    */
    public static String parseTokenGetUserId(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody()
                .getId();
    }
    /**
     * @description 验证token是合法
     * @author 莫若省
     * @createTime 2024/5/6
    */
    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
            //凭证到期情况
        } catch (ExpiredJwtException e) {
            return true;
            //token格式不正确情况
        }catch (MalformedJwtException e) {
            return false;
        }
    }
}
